package myJs.components

import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.extra.StateSnapshot
import japgolly.scalajs.react.vdom.all._
import myJs.myPkg.jquery._
import org.scalajs.dom.html

/**
 * Created by yz on 3/11/2020
 */
object PureInputComponent {

  case class Props(state: StateSnapshot[String], name: String, formJq: JQuery = $("#form"), readOnly: Boolean = false) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  class Backend(bs: BackendScope[Props, Unit]) {

    private val inputRef = Ref[html.Input]

    def didMount(p: Props): Callback = {
      inputRef.foreach { y =>
      }
    }

    def unmount(p: Props): Callback = {
      inputRef.foreach { y =>
      }
    }

    def render(p: Props) = {

      def valueChange(e: ReactEventFromInput) = {
        val myValue = e.target.value
        p.state.modState(x => myValue)
      }

      val s = p.state.value
      input(`type` := "text", `class` := "form-control fillByName", name := s"${p.name}", value := s"${s}",
        onChange ==> valueChange,readOnly:=p.readOnly).withRef(inputRef)
    }

  }

  val Component = ScalaComponent.builder[Props].renderBackend[Backend].
    componentDidMount(x => x.backend.didMount(x.props)).componentWillUnmount(x => x.backend.unmount(x.props)).
    build

}



